package com.resou.reader.search.adpter;

import android.support.annotation.Nullable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.resou.reader.R;
import com.resou.reader.api.entry.SearchBean;

import java.util.List;

/**
 * Author: 萤火虫
 * E-mail:  Allensuns@163.com
 * Description:BaseQuickAdapter开源通用适配器
 * 请参考https://www.jianshu.com/p/b343fcff51b0
 * CreateTime: 2019-03 -15
 **/
public class SearchKeyWordAdapter extends BaseQuickAdapter<SearchBean, BaseViewHolder> {

    String courceText = "";

    public SearchKeyWordAdapter(int layoutResId, @Nullable List<SearchBean> data, String courceText) {
        super(layoutResId, data);
        this.courceText = courceText;
    }

    public SearchKeyWordAdapter(@Nullable List<SearchBean> data, String courceText) {
        super(data);
        this.courceText = courceText;
    }

    public SearchKeyWordAdapter(int layoutResId) {
        super(layoutResId);
    }

    @Override
    protected void convert(BaseViewHolder helper, SearchBean item) {
        spanString(helper.getView(R.id.tvKeyWord), item.getNovelName(), courceText);
        helper.addOnClickListener(R.id.llOnclick);
    }

    /**
     * 将文本的关键字 设置为红色
     *
     * @param textView 控件实例
     * @param text     关键字
     */
    private void spanString(TextView textView, String text, String sourceText) {
        SpannableStringBuilder sbb = new SpannableStringBuilder(text);
        for (int i = 0; i < text.length(); i++) {
            String temp = text.substring(i, i + 1);
            if (sourceText.contains(temp)) {
                sbb.setSpan(new ForegroundColorSpan(textView.getResources().getColor(R.color.btn_login_highlight)), i, i + 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);//Color.parseColor("#ffc36a")
            }
        }
        textView.setText(sbb);
    }
    public void setData(@Nullable List<SearchBean> data, String courceText) {
        setNewData(data);
        this.courceText = courceText;
    }
}
